<?php
/**
 * @copyright Arthur Beer
 * @package core.config
 *
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
 /**
  * Config
  */
class Config extends Object
{
    private static $instances   = array();
    
    /**
     * SimpleXML
     *
     * @var SimpleXMLElement
     */
    private $xml;
    
    private $path   = FRAMEWORK_REGISTRY_PATH;
    
    /**
     * Конструктор класса
     * 
     */
    private function __construct($namespace)
    {
        if(!($namespace = $this->getNamespace($namespace))) {
            throw new Exception('Config: Initialize by empty namespace failed.');
        }
        
        $namespace = str_replace("\\", "/", $namespace);
        $schema = parse_url($namespace);
        $this->path = ( array_key_exists('scheme', $schema) ? $schema['path'] : $this->path . '/' . $schema['path'] ) . '.xml';

        if(!file_exists($this->path)) {
            throw new Exception("Config: Namespace not found ($namespace); initialize failed ($this->path).");
        }
        
        $this->xml = simplexml_load_file($this->path);
    }
    
    /**
     * Возвращает узел свойства или все дерево
     * настроек указанного namespace.
     *
     * @param string $query
     * @param string $namespace
     * @return ConfigProperty
     */
    public static function get($query = null, $namespace = null)
    {
        if(!array_key_exists($namespace, self::$instances)) {
            self::$instances[$namespace] = new Config($namespace);
        }
        
        return self::$instances[$namespace]->find($query);
    }
    
    /**
     * Возвращает узел свойства.
     *
     * @param string $query
     * @return ConfigProperty
     */
    public function find($query = null)
    {
        $property = new ConfigProperty($this->xml);
        if(!$query) {
            return $property;
        }

        foreach (explode('/', $query) as $name) {
            $property = $property->$name;
        }
        
        return $property;
    }
}

/**
 * Tab: 4 spaces
 * Encoding: utf-8
 */
?>